'use strict';
const url = require('url');
const crypto = require('crypto');
const moment = require('moment');

module.exports = {
  /* eslint no-bitwise: 0 */
  /**
   * ip转数字
   * @param {String} ip ip地址
   * @return {Number} 返回转换后的数值
   */
  ip2int(ip) {
    let num = 0;
    ip = ip.split('.');
    num = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3]);
    num = num >>> 0;
    return num;
  },
  /**
   * 数字转ip
   * @param {Number} num 这里是描述
   * @return {String|*} 返回IP地址
   */
  int2ip(num) {
    const tt = [];
    tt[0] = (num >>> 24) >>> 0;
    tt[1] = ((num << 8) >>> 24) >>> 0;
    tt[2] = (num << 16) >>> 24;
    tt[3] = (num << 24) >>> 24;
    const str = String(tt[0]) + '.' + String(tt[1]) + '.' + String(tt[2]) + '.' + String(tt[3]);
    return str;
  },
  /**
   * Authorization 生成函数
   * @param {String} access_token 通过接口获取到的认证token
   * @param {String} mac_key 通过接口获取到的加密key
   * @param {String} request_uri 接口请求地址，例如：http://aqapi.101.com/v0.93/users/520414
   * @param {String} request_method 接口调用方式，例如：POST
   * @return {String} 返回 authorization 字符串，例如：MAC id="26F411203509A38FBD0EC2B21E93B3168473119D387C78CDBCD9BCC90604E0313EBBA1547622DF65",nonce="1475114936431:HGQ1GX5Q",mac="sxI4BupKW0IGn2HyIAzjv4EXy7DwpVLQOe5/SA9uJfQ="
   */
  genAuthHeader(access_token, mac_key, request_uri, request_method) {
    let strAuth = 'MAC id="' + access_token + '",nonce="';
    const nonce = new Date().getTime() + ':' + this.randomCode();
    strAuth += nonce + '",mac="';
    const host = url.parse(request_uri).hostname;
    const path = url.parse(request_uri).pathname;
    const request_content = nonce + '\n' + request_method + '\n' + path + '\n' + host + '\n';
    const hmac = crypto.createHmac('sha256', mac_key).update(request_content).digest('base64');
    strAuth += hmac + '"';
    return strAuth;
  },

  /**
   * @description 时间格式化
   * @author xiezuobing[948466]<435321508@qq.com>
   * @param {any} date_str 
   * @param {string} [format='YYYY-MM-DD HH:mm:ss'] 
   * @returns  
   */
  formatDate(date_str, format = 'YYYY-MM-dd HH:mm:ss') {
    return moment(new Date(date_str)).utcOffset(0).format(format);
  },

  /**
   * 随机生成字符串
   * @return {String} 返回随机字符串
   */
  randomCode() {
    let code = '';
    const codeLength = 8;
    const chars = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

    for (let i = 0; i < codeLength; i++) {
      const charIndex = Math.floor(Math.random() * 36);
      code += chars[charIndex];
    }
    return code;
  },
  /**
   * 将 unix 转换成正常的日期格式
   * @param {Number} unix_time unix 时间格式
   * @param {String} format more config see momentjs document
   * @return {Date} 返回格式化后的时间
   */
  unix2date(unix_time, format) {
    format = format || 'YYYY-MM-DD HH:mm:ss';
    return moment.unix(unix_time).format(format);
  },
  /**
   * 将正常的日期格式转换成 unix
   * @param {Date} date 正常时间格式时间
   * @return {Number} 返回 unix 时间戳
   */
  date2unix(date) {
    return date ? moment(date).format('X') : moment().format('X');
  },
  // 过滤HTML标签并截断字符
  get_brief(content, length) {
    length = length || 80;
    const r = /[^\x00-\xff]/g;
    content = content.replace(/<\/?[^>]*>/g, ''); //去除HTML tag
    content = content.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
    content = content.replace(/&nbsp;/ig, ''); //去掉&nbsp;
    if (content.replace(r, "mm").length <= length) {
      return content;
    }
    const m = Math.floor(length / 2);
    for (let i = m; i < content.length; i++) {
      if (content.substr(0, i).replace(r, "mm").length >= length) {
        return content.substr(0, i) + "...";
      }
    }
    return content;
  },
  // 网址操作
  url(ctx, params = {}, expect = []) {
    for (const item in params) {
      expect.push(item);
    }

    const params_arr = [];

    for (const key in ctx.query) {
      if (expect.indexOf(key) === -1) {
        params_arr.push(`${key}=${encodeURIComponent(ctx.query[key])}`);
      }
    }

    for (const key1 in params) {
      params_arr.push(`${key1}=${encodeURIComponent(params[key1])}`);
    }

    const url_prefix = ctx.request.url.split('?');
    if (params_arr.length > 0) {
      return url_prefix[0] + '?' + params_arr.join('&');
    }
    return ctx.request.url;
  },

  encodeURIComponent(str) {
    return encodeURIComponent(str)
  },

  getTemplateTypeByName(name) {
    switch (name) {
      case '关于华渔':
      case '华渔准则':
        return 1;
        break;

      case '关于华渔':
      case '华渔准则':
        return 1;
        break;

      case '华渔定见':
        return 2;
        break;

      case '华渔视界':
        return 3;
        break;

      case '标准文档':
      case '高层声音':
        return 4;
        break;

      case '新闻资讯':
      case '公告':
        return 5;
        break;
      default:

    }
  }

};
